package org.jivesoftware.spark.crowd.packet;

import java.util.ArrayList;
import java.util.List;

import javax.swing.Icon;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.spark.PresenceManager;
import org.jivesoftware.spark.crowd.Param;
import org.jivesoftware.spark.crowd.ui.UIEventManager;
import org.jivesoftware.spark.ui.PresenceListener;

public class CrowdsPresenceManager {
	/**
	 * singleton mode ,support only one service name.
	 */
	private static CrowdsPresenceManager instance;
	private Connection conn;
	private String crowdServiceName;

	/**
	 * listeners to change members' presence
	 */
	private List<PresenceUpdater> presenceUpdaters = new ArrayList<PresenceUpdater>();
	public static CrowdsPresenceManager getInstance(Connection conn,String serviceName){
		if(instance == null)
			instance = new CrowdsPresenceManager(conn,serviceName);
		return instance;		
	}
	public static CrowdsPresenceManager getInstance(){
		return instance;
	}
	private CrowdsPresenceManager(Connection conn,String serviceName){
		this.conn = conn;
		this.crowdServiceName = serviceName;
		
		init();
	}
	private void init(){
		final String serverDomain = conn.getServiceName();
		PacketFilter ptf = new PacketTypeFilter(Presence.class);
		PacketListener ppl = new PacketListener(){
			@Override
			public void processPacket(Packet packet) {			
				Presence newPresence = null;
				if(packet instanceof Presence){
					newPresence = (Presence)packet;					
					if(StringUtils.parseServer(newPresence.getFrom()).equals(serverDomain)){
						for(PresenceUpdater pu : presenceUpdaters){
							pu.crowdPresenceChanged(newPresence);
						}
					}
				}
				
			}			
		};
		conn.addPacketListener(ppl, ptf);
		
		PresenceListener pl = new PresenceListener(){
			@Override
			public void presenceChanged(Presence presence) {
				UIEventManager.getInstance().handleSelfPresenceChanged(presence);
			}
			
		};
		Param.getSessionManager().addPresenceListener(pl);
		
	}
	public void addCrowdPresenceUpdater(PresenceUpdater pu){
		if(!presenceUpdaters.contains(pu))
			presenceUpdaters.add(pu);
	}
	
	public void removePresenceUpdater(PresenceUpdater pu){
		presenceUpdaters.remove(pu);
	}
	
	public static interface PresenceUpdater{
		public void crowdPresenceChanged(Presence newPresence);
	}
	
	
}
